package top.chenfu.blog.service.impl;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.chenfu.blog.dao.CategoryMapper;
import top.chenfu.blog.entity.Category;
import top.chenfu.blog.service.CategoryService;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Auther chenfu
 * @2019/10/31 20:40
 * @Desc
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAll();
    }

    @Override
    @Transactional
    public Integer addCategory(Category category) {
        if (CollectionUtils.isNotEmpty(categoryMapper.select(category))) {
            return 1;
        }
        category.setDate(new Timestamp(System.currentTimeMillis()));
        return categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public Integer updateCategory(Category category) {
        return categoryMapper.updateByPrimaryKeySelective(category);
    }

    @Override
    @Transactional
    public Boolean deleteCategoryByIds(String ids) {
        List<String> cateIds = Arrays.asList(ids.split(","));
        int delCount = (int) cateIds.stream().map(id -> categoryMapper.deleteByPrimaryKey(id)).count();
        return delCount == cateIds.size();
    }

}
